#!/usr/bin/env python
# -*- coding: utf-8 -*-

#    This file is part of My Text Editor.
#
#    My Text Editor is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    My Text Editor is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with My Text Editor.  If not, see <http://www.gnu.org/licenses/>.

# Copyright (C) 2013 Joseba García Etxebarria <joseba.gar@gmail.com>. All rights reserved.

"""This file includes a class for managing preferences.
The preferences are managed in a per-user basis and are stored
in each user's private dir."""

import os, sys, sqlite3

class preferences():
    # Check whether the prefs file already exists and initialize it
    # otherwise
    def __init__(self):
        if sys.platform.startswith('win'):
            self.dbpath = os.getenv('APPDATA')+'/blockeditor/prefs.sqlite'
        elif sys.platform == 'darwin':
            self.dbpath = os.getenv('HOME')+'/Library/Application Support/blockeditor/prefs.sqlite'
        else:
            self.dbpath = os.getenv('HOME')+'/.config/blockeditor/prefs.sqlite'
        
        # If the file already exists, refuse to try to intialize it
        if os.path.isfile(self.dbpath):
            return
        
        if not os.path.isdir(os.path.dirname(self.dbpath)):
            # We should always be able to write to our own directory...
            try:
                os.makedirs(os.path.dirname(self.dbpath))
            except OSError:
                sys.stderr.write("Couldn't initialize %s, sorry\n" % self.dbpath)
                return
        
        # Debug
        print(self.dbpath+" doesn't exists, creating it")
        
        # DB doesn't exist => initialize it
        try:
            conn = sqlite3.connect(self.dbpath)
        except OperationalError:
            sys.stderr.write("Couldn't initialize %s, sorry\n" % self.dbpath)
            return
        
        # Create the cursor, then initialize the DB
        c = conn.cursor()
        c.execute("""CREATE TABLE 'preferences'
            ('id' INTEGER PRIMARY KEY AUTOINCREMENT,
            'preference' text, 'value' text)""")
        conn.commit()
        c.close()

    def get(self, preference):
        "Get value for given preference from the DB"
        
        # Conect to the prefs DB
        try:
            conn = sqlite3.connect(self.dbpath)
        except OperationalError:
            sys.stderr.write("Couldn't open preferences DB sorry\n")
            return 1
        
        c = conn.cursor()
        # execute the query
        t = (preference,)
        c.execute("SELECT value from preferences WHERE preference=? LIMIT 1", t)

        value = c.fetchone()
        conn.commit()
        c.close()
        
        # Preference doesn't exist
        if value == None:
            return ''

        # Return value
        return value[0]
    
    def set(self, preference, value=''):
        """ Set value for given preference from the DB.
        If the preference doesn't already exist, set it"""
        # Conect to the prefs DB
        try:
            conn = sqlite3.connect(self.dbpath)
        except OperationalError:
            sys.stderr.write("Couldn't open preferences DB sorry\n")
            return 1
        
        c = conn.cursor()
        # Set or create the VALUE in the DB
        t = (value, preference,)
        if self.get(preference) is '':
            c.execute("INSERT INTO 'preferences' (value, preference) VALUES (?, ?)", t)
        else:
            c.execute("UPDATE 'preferences' set value=? WHERE preference=?", t)
            
        conn.commit()
        c.close()

